# -*- coding: utf-8 -*-
"""
@Time ： 2021/5/6 21:34
@Auth ： Mr. royalday 2487625775
@Company ：XXX
@Function ：wiki的所有视图
"""
import json
import time

from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from web import models
from web.forms.wiki import WikiModelForm
from django.views.decorators.csrf import csrf_exempt  # 装饰器，对函数不进行安全校验
from utils.tencent import cos
from utils import encrypt
from django.views.decorators.clickjacking import xframe_options_sameorigin


def wiki(request, project_id):
    """
    项目主页-文档页面
    :param request:
    :param project_id: 项目id
    :return:
    """
    wiki_id = str(request.GET.get('wiki_id'))
    if not isinstance(eval(wiki_id), int):
        return render(request, 'manage/wiki.html')
    if wiki_id and wiki_id.isdecimal():
        wiki_object = models.Wiki.objects.filter(id=wiki_id, project_id=project_id).first()
    else:
        wiki_object = None

    return render(request, 'manage/wiki.html', {'wiki_object': wiki_object})


def wiki_add(request, project_id):
    """
    新增wiki文档页面
    :param request:
    :param project_id:
    :return:
    """
    request.wiki_method = 'add'
    request.tracer.project.wiki_id = None
    form = WikiModelForm(request)
    if request.method == "GET":
        return render(request, 'manage/wiki_form.html', {'form': form})
    if request.method == "POST":
        form = WikiModelForm(request, request.POST)
        if form.is_valid():
            # 由于文章有编辑功能，需要做个判断
            # 判断用户是否选中了父文章，如果是则当前文章的深度等于父文章的深度+1, 否则为1
            if form.instance.parent:
                form.instance.depth = form.instance.parent.depth + 1
            else:
                form.instance.depth = 1

            form.instance.project = request.tracer.project
            form.save()
            url = reverse('web:wiki', kwargs={'project_id': project_id})
            return redirect(url)
    return render(request, 'manage/wiki_form.html', {'form': form})


def wiki_catalog(request, project_id):
    """
    项目内wiki文档的目录
    :param request:
    :param project_id:
    :return:
    """
    # 获取当前项目的所有wiki文档
    data_list = models.Wiki.objects.filter(project_id=project_id).values('id', 'title', 'parent_id').order_by(
        'depth', 'id')

    return JsonResponse({'status': True, 'data': list(data_list)})


def wiki_detail(request, project_id):
    request.wiki_method = 'detail'
    """
    wiki详情页,如果优化，可以直接在wiki函数中设置即可，这里为了理清思路，做下调用
    :param request:
    :param project_id:
    :return:
    """
    res = wiki(request, project_id)
    return res


def wiki_delete(request, project_id, wiki_id):
    request.wiki_method = 'delete'
    request.tracer.project.wiki_id = wiki_id
    if not isinstance(eval(wiki_id), int):
        return render(request, 'manage/wiki.html')
    if wiki_id:
        models.Wiki.objects.filter(id=wiki_id, project_id=project_id).delete()
    return render(request, 'manage/wiki.html')


def wiki_edit(request, project_id, wiki_id):
    """
    编辑文章
    :param request:
    :param project_id:
    :param wiki_id:
    :return:
    """
    request.wiki_method = 'edit'
    wiki_object = None
    wiki_id = eval(wiki_id)
    if not isinstance(wiki_id, int):
        return render(request, 'manage/wiki.html')
    if wiki_id:
        request.tracer.project.wiki_id = wiki_id
        wiki_object = models.Wiki.objects.filter(id=wiki_id, project_id=project_id).first()
    if wiki_object:
        if request.method == 'GET':
            form = WikiModelForm(request, instance=wiki_object)
            return render(request, 'manage/wiki_form.html', {'form': form})
        if request.method == 'POST':
            form = WikiModelForm(request, data=request.POST, instance=wiki_object)
            if form.is_valid():
                # 由于文章有编辑功能，需要做个判断
                # 判断用户是否选中了父文章，如果是则当前文章的深度等于父文章的深度+1, 否则为1
                if form.instance.parent:
                    form.instance.depth = form.instance.parent.depth + 1
                else:
                    form.instance.depth = 1

                form.instance.project = request.tracer.project
                form.save()
                # 修改成功后，直接跳转到当前wiki的预览页面
                url = reverse('web:wiki', kwargs={'project_id': project_id})
                preview_url = url + '?wiki_id=' + str(wiki_id)
                return redirect(preview_url)
    return render(request, 'manage/wiki.html')


@xframe_options_sameorigin
@csrf_exempt
def wiki_upload(request, project_id):
    """
    markdowm上传突破的视图
    :param request:
    :param project_id:
    :return:
    """
    result = {
        'success': 0,
        'message': None,
        'url': None
    }

    # 获取上传的图片对象
    image_object = request.FILES.get('editormd-image-file')
    if not image_object:
        result['message'] = "文件不存在！！！"
        return JsonResponse(result)

    # 将突破上传到cos桶中
    bucket = request.tracer.project.bucket
    region = request.tracer.project.region
    # 生成随机字符串
    uid = encrypt.uid(image_object.name.rsplit('.')[0:-1])
    # 获取时间戳
    time_stamp = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
    # 获取文件后缀
    img_ext = image_object.name.rsplit('.')[-1]
    key = f"{uid}-{time_stamp}.{img_ext}"

    img_url = cos.upload_buffer_file(bucketName=bucket, region=region, file_object=image_object, key=key)
    result['success'] = 1
    result['url'] = img_url

    return JsonResponse(result)
